package model

import (
	"aquaman/app/infra/ecode"
	"github.com/gocraft/dbr/v2"
	"github.com/pkg/errors"
)

type Train struct {
	Name 			string
	Type			string
	DepartOn 		string
	ArriveAt		string
	Begin			string
	End				string
	Price			int64
	StationCount 	int64
}

type TrainV2 struct {
	Name 			string
	Type			string
	JSW				string
	JSYQ			string
	TL				string
	YX				string
	CD				string
	XQ				string
	CS				string
	SHN 			string
	Direction		int64
	Scheme			int64
}


func (repo *Repository) GetTrainsV2(scheme uint64,departOn string,stationKey string,endStationKey string, direction int64) (list []TrainV2) {
	session := repo.db.NewSession(nil)
	var schemeBuilder dbr.Builder
	if scheme == 1 {
		schemeBuilder = dbr.Or(
				dbr.Eq("scheme",1),
				dbr.Eq("scheme",2),
			)
	}else if scheme == 2 {
		schemeBuilder = dbr.Eq("scheme",1)
	}
	_,err := session.Select("*").
		From("js_train_v2").
		Where(dbr.And(
			schemeBuilder,
			dbr.Eq("direction",direction),
			dbr.Gte(stationKey,departOn),
			dbr.Gte(endStationKey,departOn),
			)).
		OrderAsc(stationKey).
		Load(&list)
	if err != nil {
		//panic(err)
		//panic(ecode.Error(ecode.TrainQueryError,err.Error()))
		panic(errors.Wrap(ecode.TrainQueryError,err.Error()))
	}

	return
}


func (repo *Repository) GetTrains(scheme uint64,departOn string,begin string,end string) (list []Train) {
	session := repo.db.NewSession(nil)
	_, err := session.Select("*").
		From("js_train").
		Where(dbr.And(
			dbr.Eq("scheme",scheme),
			dbr.Eq("begin",begin),
			dbr.Eq("end",end),
			dbr.Gte("depart_on",departOn),
			)).OrderAsc("depart_on").
		Load(&list)
	if err != nil {
		//panic(err)
		//panic(ecode.Error(ecode.TrainQueryError,err.Error()))
		panic(errors.Wrap(ecode.TrainQueryError,err.Error()))
	}
	return
}
